import React, { useState, useEffect } from 'react';
import { cline, obj_str, useCmd, uDb, is_empty, obj_empty, loc } from 'sui';
import { load_item } from './cmd';
import { Bind } from './ctl';

const BindEquip = ({ cur, hreturn }) => {
    const [main_user, mainUser] = useState([]);
    const [checked, setChecked] = useState([]);
    const umd = useCmd();

    useEffect(() => {
        load_item(null, cur, umd.setValue, "getequip");
        uDb(null, "equip/list", {line: cline()}, r => mainUser(r), e => mainUser(null));
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [cur]);

    const remove = (v) => {
        uDb(null, "station/rmequip",
            {
                line: cline(),
                k: obj_str(cur, "sn"),
                sn: v,
            },
            r => {
                load_item(umd.endWait, cur, umd.setValue, "getequip");
                setChecked([]);
            },
            e => umd.setErr(loc("l_253")), true);
    };

    const addUser = () => {
        if (obj_empty(cur) || is_empty(checked)) {
            return;
        }

        umd.startWait();

        uDb(null, "station/addequip",
            {
                line: cline(),
                k: obj_str(cur, "sn"),
                v: checked,
            },
            r => {
                load_item(umd.endWait, cur, umd.setValue, "getequip");
                setChecked([]);
            },
            e => umd.setErr(loc("l_253")), true);
    };

    return <Bind umd={umd} cur={cur} hreturn={hreturn} hadd={addUser} checked={checked} setChecked={setChecked} title={loc("l_145")}
                 hremove={remove} main={main_user} setMain={mainUser}/>;
};

export {BindEquip};
